package cn.qingfeng.a003_chat_v2.server.handler;

import cn.qingfeng.a003_chat_v2.message.GjoinRequestMessage;
import cn.qingfeng.a003_chat_v2.server.groupsession.Group;
import cn.qingfeng.a003_chat_v2.server.groupsession.GroupSession;
import cn.qingfeng.a003_chat_v2.server.groupsession.GroupSessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class GjoinHandler extends SimpleChannelInboundHandler<GjoinRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GjoinRequestMessage msg) throws Exception {
        final GroupSession groupSession = GroupSessionFactory.getSession();

        if (msg == null) {
            return;
        }

        String username = msg.getFromUsername();
        String groupName = msg.getGroupName();
        Group group = groupSession.joinMember(groupName, username);
        if (group != null) {
            ctx.writeAndFlush(groupName + "群加入成功");
        } else {
            ctx.writeAndFlush(groupName + "群不存在");
        }
    }
}